<?php

require_once WACT_ROOT . 'controller/controller.inc.php';
require_once WACT_ROOT . 'controller/form.inc.php';
require_once WACT_ROOT . 'validation/rules/match.inc.php';
require_once WACT_ROOT . 'validation/rules/member.inc.php';
require_once WACT_ROOT . 'validation/rules/pattern.inc.php';
require_once APP_ROOT . 'model/common/video.php';
require_once APP_ROOT . 'model/common/statdivisions.php';
require_once APP_ROOT . 'model/common/statscores.php';
require_once APP_ROOT . 'model/common/statteams.php';
require_once APP_ROOT . 'model/common/categories.php';
require_once APP_ROOT . 'model/common/session.php';
require_once APP_ROOT . 'model/common/form.php';
require_once APP_ROOT . 'model/common/user.php';
require_once APP_ROOT . 'model/common/date.php';
require_once APP_ROOT.'include/inc.config.php';


// scores create/update form
class ScoresFormController extends FormController {

	var $admin_user = false;
	var $staff_user = false;
	var $view; // current view

	function setUserType($admin_user=false, $staff_user = false) {
		$this->admin_user = $admin_user;
        $this->staff_user = $staff_user;
	}

    function setView(&$view) {
    	$this->view = $view;
    }


	 function ScoresFormController() {
     	$this->addChild('create', new ButtonController(new Delegate($this, 'create'))); // create
        $this->addChild('save', new ButtonController(new Delegate($this, 'save'))); // save
        $this->addChild('delete', new ButtonController(new Delegate($this, 'delete'))); // delete

        $this->addChild('clean', new ButtonController(new Delegate($this, 'clean'))); // clean
        $this->addChild('scores', new ButtonController(new Delegate($this, 'back'))); // clean

        $this->setDefaultChild('clean');

        // validation
		$this->addRule(new Handle('RequiredRule', array('gameName')));
        $this->addRule(new Handle('SizeRangeRule', array('gameName', 112)));
        $this->addRule(new PatternRule('score1','/^[0-9]{1,4}$/'));
        $this->addRule(new PatternRule('score2','/^[0-9]{1,4}$/'));
        $this->addRule(new Handle('RequiredRule', array('score1')));
        $this->addRule(new Handle('RequiredRule', array('score2')));


        $this->registerOnLoadListener(new Delegate($this, 'load'));
        //$this->registerOnActivateListener(new Delegate($this, 'check'));

        $this->addView('delete', new Handle('RedirectView', array('/delete')));

	 }

	 function checkTeams(&$source, &$request, &$responseModel) {
        	// check that two teams are within the same division
            $team1ID = $responseModel->get('team1ID');
            $team2ID = $responseModel->get('team2ID');

            //print $category_id.'/'.$category2_id ;

            if (!$team1ID || !$team1ID) {
                $responseModel->set('msg',"Error: Teams must be selected!");
            	return false;
            }
            if ($team1ID == $team2ID) {
                $responseModel->set('msg',"Error: Teams must be different!");
            	return false;
            }


            if ($team1ID && $team2ID) {
            	$linked = StatTeam::AreTeamsInDivision($team1ID, $team2ID);
            	//print 'result of check '.$linked;
            	if (!$linked) {
                    $responseModel->set('msg',"Error: The teams should be within one division!");
                    //print $category_id.'/'.$category2_id." Not Linked!";
            		return false;
            	}
            }
            return true;
     }

	 function makeGameDate(&$responseModel) {
            //prepare show_date
            $day = $responseModel->get('gameDay');
            $month = $responseModel->get('gameMonth');
            $year = $responseModel->get('gameYear');

            if ($day>0 && $month>0 && $year>2000) {
            	$gameDate = gmmktime(0,0,0, $month,$day,$year);
                //$tz =& new MyTimeZone();
            	//$date_show = $tz->timeLocal($date_show);
                $responseModel->set('gameDate',gmdate("Y-m-d",$gameDate));
            }
	 }


     function create(&$source, &$request, &$responseModel) {
     	if ($responseModel->isValid()) {
            require_once WACT_ROOT.'/util/phpcompat/clone.php';

            if (!$this->checkTeams($source, $request, $responseModel) ) return 'this';


            $tz =& new MyTimeZone();
            $responseModel->set('date_added', gmdate("Y-m-d H:i", $tz->timeNowLocal() ) );

            //prepare show_date
            $this->makeGameDate($responseModel);


            $scoreID = Score::insertScore($responseModel);
            if ($scoreID) {
            	$responseModel->set('scoreID', $scoreID);
                $lastRecord = clone_obj($responseModel);


                // Set up the model for adding the next record
                $responseModel->removeAll();
                $responseModel->set('LastRecord', $lastRecord);

                return 'createOK';
            } else {
                return 'failure';
            }
        } else {

        }
     }


	 function delete(&$source, &$request, &$responseModel) {
	 	return 'delete';
	 }

	 function enable(&$source, &$request, &$responseModel) {
        $scoreID = $request->getParameter('scoreID');
	 	//print 'Activating Team: '.$teamID;
	 	if ($scoreID) {
	 		Score::publishScore($scoreID);
	 		$responseModel->set('enabled_show', 1);
	 	}

	 	return 'this';
	 }

     function disable(&$source, &$request, &$responseModel) {
        $scoreID = $request->getParameter('scoreID');
	 	//print 'DeActivating Team: '.$teamID;
	 	if ($scoreID) {
	 		Score::denyScore($scoreID);
	 		$responseModel->remove('enabled_show');
	 	}

	 	return 'this';
	 }



     function save(&$source, &$request, &$responseModel) {
        if ($responseModel->isValid()) {
        	$scoreID = $request->getParameter('scoreID');

        	if (!$this->checkTeams($source, $request, $responseModel) ) return 'this';


            //prepare game date
            $this->makeGameDate($responseModel);


        	//prepare admin user
            $admin_user_id = 0;
            if (Session::isLogin()) {
            	$admin_user_id = Session::getUserId();
            }
            if ($admin_user_id) $responseModel->set('admin_user_id',$admin_user_id);


            if ($scoreID) Score::updateScore($scoreID, $responseModel);
            return 'saveOK';
        }
    }

    function clean(&$source, &$request, &$responseModel) {
        $responseModel->removeAll();
        $responseModel->set('supress_errors', 1);
    	return 'cleanOK';
    }

    function back(&$source, &$request, &$responseModel) {
        $responseModel->removeAll();
        $responseModel->set('supress_errors', 1);
    	return 'index';
    }

     // load Game Date
    function loadGameDate(&$responseModel) {
       if ($responseModel->hasProperty('gameDate')) {
       		$date_show = $responseModel->get('gameDate');
       		//print $date_show;
       		//print strtotime($date_show);
       		$ts = strtotime($date_show);
            $tz =& new MyTimeZone();
            $ts = $tz->timeGMT($ts);
       		$day = (integer)gmdate('d',$ts);
       		$month = (integer)gmdate('m',$ts);
       		$year = (integer)gmdate('Y',$ts);
       		//print "   ".$day."/".$month."/".$year;
       		if ($day>0) $responseModel->set('gameDay',$day);
            if ($month>0) $responseModel->set('gameMonth',$month);
            if ($year>0) $responseModel->set('gameYear',$year);
       }

    }



    function load(&$source, &$request, &$responseModel) {
     	$scoreID = $request->getParameter('scoreID');
     	//print 'from load: user-id='.$user_id;
     	if ($scoreID) {
        	$record =& Score::getRecord($scoreID);
        	if (is_null($record)) {
            	return 'notfound';
        	}
            $responseModel->import($record->export());

            $enabled = $record->get('enabled');
            if (!$enabled) $responseModel->remove('enabled');

            $this->loadGameDate($responseModel);
        }
     }

     //prepare the form view
     function prepare(&$source, &$request, &$responseModel, &$template) {
     	//print 'Prepare form...';
     	$scoreID = $request->getParameter('scoreID');
     	if ($this->admin_user) {
     		$responseModel->set('admin_user',1);
     	}
     	if ($this->staff_user) $responseModel->set('staff_user',1);
        $responseModel->set('host',HOST);
        if (!$scoreID) $responseModel->set('enabled',1);

        // $responseModel->set('enabled',1);


        // determine the current user
        if (Session::isLogin()) {
        	$user_id = Session::getUserId();
        	$isAuthor = User::isUserArticleWriter($user_id);
        	$isAdmin =  User::isUserAdmin($user_id);
        }

        if ($isAuthor) $responseModel->set('author_user',1);

        //populate teams
        $teams =& StatTeam::getTeamsForList();
        //print_r($divisions);
        $team1 =& $template->getChild('team1ID');
        $team2 =& $template->getChild('team2ID');
        $team1->setChoices($teams);
        $team2->setChoices($teams);

         // populate season Years
        $years =& StatTeam::getSeasonYears();
        $season =& $template->getChild('seasonYear');
        $season->setChoices($years);

         //populate months
        $gameMonth =& $template->getChild('gameMonth');

        $months_list =& SportDate::getMonthsList();
        $gameMonth->setChoices($months_list);

        //print_r($responseModel);


        //prepopulate date
        $tz =& new MyTimeZone();
        $now = $tz->timeNowLocal();
        $cur_month = (integer)date("m",$now);
        $cur_year = (integer)date("Y",$now);
        $cur_day = (integer)date("d",$now);

        if ( $cur_month==1 ) {
        	$prev_month = 12;
        	$prev_year = $cur_year-1;
        }  else {
           $prev_month = $cur_month - 1;
           $prev_year = $cur_year;
        }

        if ( $cur_month==12 ) {
        	$next_month = 1;
        	$next_year = $cur_year+1;
        }  else {
           $next_month = $cur_month + 1;
           $next_year = $cur_year;
        }

        $gameDay =& $template->getChild('gameDay');
        $day = $gameDay->getValue();
        if (!$day) $gameDay->setValue($cur_day);

        if ($gameMonth->getValue()<=0) $gameMonth->setSelection($cur_month);


        $gameYear =& $template->getChild('gameYear');
        $year = $gameYear->getValue();
        if (!$year) $gameYear->setValue($cur_year);




     }



}

?>